package cmd

import (
	"context"
	"gf-demo/internal/consts"
	"gf-demo/internal/controller/lineBasic"
	"gf-demo/internal/controller/locale"
	"gf-demo/internal/controller/login"
	"gf-demo/internal/controller/register"
	"gf-demo/internal/controller/sys_user"
	"gf-demo/internal/model"
	"gf-demo/internal/service"
	"github.com/goflyfox/gtoken/gtoken"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/net/goai"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gctx"

	"gf-demo/internal/controller/hello"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			//设置默认语言
			consts.I18n.SetLanguage(consts.DefaultLocale)
			//配置http服务
			s := g.Server()
			s.Use(ghttp.MiddlewareHandlerResponse)
			s.Group("/", func(group *ghttp.RouterGroup) {
				// Group middlewares.
				group.Middleware(
					service.Middleware().Ctx,
					ghttp.MiddlewareCORS,
				)
				// Register route handlers.
				var (
					registerCtrl  = register.NewV1()
					loginCtrl     = login.NewV1()
					helloCtrl     = hello.NewV1()
					userCtrl      = sys_user.NewV1()
					lineBasicCtrl = lineBasic.NewV1()
					localeCtrl    = locale.NewV1()
				)
				group.Bind(
					registerCtrl, loginCtrl, helloCtrl, userCtrl, lineBasicCtrl, localeCtrl,
				)
				// Special handler that needs authentication.
				group.Group("/", func(group *ghttp.RouterGroup) {
					group.Middleware(service.Middleware().Auth)
					group.ALLMap(g.Map{
						"/hello":     helloCtrl,
						"/user":      userCtrl,
						"/lineBasic": lineBasicCtrl,
					})
				})
			})
			// Custom enhance API document.
			enhanceOpenAPIDoc(s)
			// Just run the server.
			s.Run()
			return nil
		},
	}
)

func enhanceOpenAPIDoc(s *ghttp.Server) {
	openapi := s.GetOpenApi()
	openapi.Config.CommonResponse = ghttp.DefaultHandlerResponse{}
	openapi.Config.CommonResponseDataField = `Data`

	// API description.
	openapi.Info = goai.Info{
		Title:       consts.OpenAPITitle,
		Description: consts.OpenAPIDescription,
		Contact: &goai.Contact{
			Name: "GoFrame",
			URL:  "https://goframe.org",
		},
	}
}

func Login(r *ghttp.Request) (string, interface{}) {
	username := r.Get("Name").String()
	password := r.Get("Password").String()
	// 进行登录校验
	err := service.User().SignIn(gctx.New(), model.UserSignInInput{
		Name:     username,
		Password: password,
	})
	if gerror.Code(err).Code() != 0 {
		r.Response.WriteJson(gtoken.Fail(gerror.Code(err).Message()))
		r.ExitAll()
	}
	/**
	  返回的第一个参数对应：userKey
	  返回的第二个参数对应：data
	  {
	      "code": 0,
	      "msg": "success",
	      "data": {
	          "createTime": 1652838582190,
	          "data": "1",
	          "refreshTime": 1653270582190,
	          "userKey": "王中阳",
	          "uuid": "ac75676efeb906f9959cf35f779a1d38"
	      }
	  }
	*/
	return username, ""
}
